const fs = require('fs');
const path = require('path');
var tools = require('../../../libs/tools');
var config = require(tools.rootPath + 'config');
var { connection, pool, model } = require(tools.rootPath + 'libs/model');

var controller = require(tools.rootPath + 'libs/controller.js');

//https://www.npmjs.com/package/docx-templates
//https://www.npmjs.com/package/mammoth
//https://www.npmjs.com/package/word-to-html


var createReport = require('docx-templates').default;

var mammoth = require("mammoth");

var word2html = require('word-to-html');

class docx extends controller {
    constructor() {
        super();
    }
    __call(req, res) {
        console.log(tools.tableCachePath);
        return req.MM + '/' + req.CC + '/' + req.AA;
    }
    async index(req, res) {
        if (req.ispost) {
            let content = req.body.content;
            //console.log(content);

            const template = fs.readFileSync(tools.publicPath + 'docxs/example.docx');
            const buffer = await createReport({
                template,
                data: {
                    name: 'John',
                    surname: 'Appleseed',
                    content: content,
                },
            });
            fs.writeFileSync(tools.publicPath + 'docxs/result.docx', buffer);

            return this.msg(1, 'ok', '/index/docx/preview');
        }
        res.render(req.TPL, { title: 'Express' });
    }
    async preview(req, res) {
        let d = await mammoth.convertToHtml({ path: tools.publicPath + 'docxs/result.docx' });
        console.log(d.messages);
        res.end(d.value);
        return;

        // let t = word2html(tools.publicPath + 'docxs/result.docx', { tdVerticalAlign: 'top' });
        // console.log(t);

        res.end('ok');
    }


}

module.exports = docx;